package com.suxin.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @Classname NettyServerHandler
 * @Description [ 自定义一个 Handler ]
 * @Author Tang
 * @Date 2021/1/2 23:03
 * @Created by ASUS
 */
@ChannelHandler.Sharable
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("NettyServerHandler--->" + this.hashCode());
        super.channelRegistered(ctx);
    }

    /**
     * 实际数据读取
     * @param ctx 上下文对象，含有pipeline ，通道 channel,地址
     * @param msg 就是客户端发送的数据，默认是Object
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // taskQueue中的任务会是同一个线程去执行
//        ctx.pipeline().channel().eventLoop().execute(() -> {
//            try {
//                TimeUnit.SECONDS.sleep(10);
//                System.out.println(Thread.currentThread().getName() + "task1....");
//                ctx.writeAndFlush(Unpooled.copiedBuffer("hello, client!喵喵1!", Charset.defaultCharset()));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
        // schedule taskQueue
//        ctx.pipeline().channel().eventLoop().schedule(() -> {
//            try {
//                System.out.println(Thread.currentThread().getName() + "task2....");
//                ctx.writeAndFlush(Unpooled.copiedBuffer("hello, client!喵喵2!", Charset.defaultCharset()));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }, 5, TimeUnit.SECONDS);

        System.out.println(Thread.currentThread().getName() + " server ctx = " + ctx);
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端发送的消息：" + buf.toString());
        System.out.println("客户端地址：" + ctx.channel().remoteAddress());
    }

    /**
     * 读取完毕
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, client!喵喵3!", Charset.defaultCharset()));
    }

    /**
     * 处理异常，一般是关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info(cause.getMessage());
        ctx.close();
    }
}